﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using Lb.BackDb;

namespace LB.Common
{

    /// <summary>
    /// 文本日志记录辅助类
    /// </summary>
    public class LogHelper
    {
        #region 日志目录
        const string LogDirHtml = @"<!DOCTYPE html>
<html>
	<head>
		<meta charset='UTF-8'>
		<title>日志目录</title>
		<style type='text/css'>
			.a{width:1000px; margin: 0 auto; }
			.a div{
				width: 16.666666%;
				float: left;
				height: 50px;
				line-height: 50px;
			}
		</style>
	</head>
	<body>
		<div class='a'>
			<!--日志-->
		</div>
	</body>
</html>
";
        #endregion

        #region 记录普通日志 log
        /// <summary>
        /// 记录普通日志
        /// </summary>
        /// <param name="message"></param>
        public static void Log(string message)
        {
            string temp = GenerateMessage(message, null);
            string fileName = "log_" + DateTime.Now.ToString("HH") + ".txt";
            try
            {
                string LogFolder = LogHelper.GetLogFolder();

                if (!Directory.Exists(LogFolder))
                {
                    Directory.CreateDirectory(LogFolder);
                }
                string logfile = Path.Combine(LogFolder, fileName);

                if (!File.Exists(logfile))
                {
                    WriteDirHtml(fileName, "Log日志：");
                }
                File.AppendAllText(logfile, temp, Encoding.GetEncoding("GB2312"));
            }
            catch
            {
            }
        }
        #endregion

        #region 记录错误日志 Error
        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public static void Error(string message, Exception ex = null)
        {
            string writeMessage = GenerateMessage(message, ex);
            string fileName = "error_" + DateTime.Now.ToString("HH") + ".txt";
            try
            {
                string LogFolder = LogHelper.GetLogFolder();

                if (!Directory.Exists(LogFolder))
                {
                    Directory.CreateDirectory(LogFolder);
                }
                string logfile = Path.Combine(LogFolder, fileName);
                if (!File.Exists(logfile))
                {
                    WriteDirHtml(fileName, "Error日志：");
                }
                File.AppendAllText(logfile, writeMessage, Encoding.GetEncoding("GB2312"));
            }
            catch
            {
            }
        }
        #endregion

        #region 记录日志文件列表
        /// <summary>
        /// 记录日志文件列表
        /// </summary>
        /// <param name="logfile"></param>
        private static void WriteDirHtml(string logfile, string type)
        {
            try
            {
                string dirfile = Path.Combine(LogHelper.GetLogFolder(), "index.html");
                string folder = Path.Combine("Log", DateTime.Now.ToString("yyyyMMdd"));
                string content = "";
                if (File.Exists(dirfile))
                {
                    content = File.ReadAllText(dirfile, Encoding.UTF8).Replace("<!--日志-->", string.Format("\r\n<div><a href='{0}'>{1}</a></div><!--日志-->", logfile, type + DateTime.Now.ToString("HH:00"))); ;
                }
                else
                {

                    content = LogDirHtml.Replace("<!--日志-->", string.Format("\r\n<div><a href='{0}'>{1}</a></div><!--日志-->", logfile, type + DateTime.Now.ToString("HH:00")));
                }

                File.WriteAllText(dirfile, content, Encoding.UTF8);
            }
            finally { }
        }

        private static string GetLogFolder()
        {

            //return Path.Combine(SystemParam.ConfigDir, "Log", DateTime.Now.ToString("yyyyMMdd"));
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log", DateTime.Now.ToString("yyyyMMdd"));
        }

        #endregion

        #region 生成日志内容
        /// <summary>
        /// 生成日志内容
        /// </summary>
        /// <param name="message"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string GenerateMessage(string message, object obj)
        {
            StackTrace insStackTrace = new StackTrace(true);
            StackFrame insStackFrame = insStackTrace.GetFrame(2);
            StringBuilder sbstr = new StringBuilder();
#if DEBUG
            sbstr.AppendFormat("\r\n文件名称：{0}", insStackFrame.GetFileName());
            sbstr.AppendFormat("\r\n发生行号：{0}", insStackFrame.GetFileLineNumber());
#endif
            sbstr.AppendFormat("\r\n操作类名：{0}", insStackFrame.GetMethod().ReflectedType.Name);
            sbstr.AppendFormat("\r\n方法名称：{0}", insStackFrame.GetMethod().Name);
            sbstr.AppendFormat("\r\n记录时间：{0}", DateTime.Now);
            sbstr.AppendFormat("\r\n信息描述：{0}", message);
            if (obj != null)
            {
                if (obj is Exception)
                {
                    sbstr.AppendFormat("\r\n异常信息：{0}", (obj as Exception).ToString());
                    //sbstr.AppendFormat("\r\n异常堆栈：{0}", (obj as Exception).StackTrace);
                }
                else
                {
                    sbstr.AppendFormat("\r\n异常信息：{0}", obj.ToString());
                }

            }
            sbstr.Append("\r\n====================================================================================================\r\n");

            return sbstr.ToString();
        }
        #endregion

    }
}
